class LoginController < ApplicationController
  layout "login", :except =>[:index]
  before_filter :check_authentication,:except => [:index,:signin,:forget_password]

  def index
	     url = request.subdomains
             url = params[:url] if params[:url]
	     #url = "abb"
	     #url = "ait"
	     @company = Company.find(:first,:conditions=>["url = ?",url])
	     logger.error "=============="
	     logger.error  @company
	     logger.error "=============="
             @page_title = @company.name if @company
         if request.get?
	     if cookies[:user_id].to_i > 0 
	       logged_in_user = User.find(cookies[:user_id])
	       logged_in_user.login_at = Time.now
	       logged_in_user.save
	       redirect_to '/dashboard'
	     else
               render :layout => "login"
             end
	     session[:msg]  = nil
         elsif request.post?
             if @company
	     @user = User.new( params[:user] )
		 logged_in_user = @user.try_to_login(url)
		 if logged_in_user
		    if params[:remember].to_s == "true" 
		      cookies[:user_id] = {:value=>logged_in_user.id.to_s,:expires=>1.year.from_now,:domain=>'trikr.com'}
		    else
		      session[:user_id] = logged_in_user.id.to_s
		    end
		    logged_in_user.login_at = Time.now
		    logged_in_user.save
		    #redirect_to '/dashboard'
		    redirect_to "http://#{url}.trikr.com/dashboard"
		 else
		    session[:msg] = "<font color=red>Invalid User/password</font>"
		    redirect_to "http://#{url}.trikr.com/login"
		 end
             else
		    cookies[:user_id] = nil
		    redirect_to(:controller=>'login')
             end
	  end
  end

  def logout
	     session[:user_id] = nil
	     cookies[:user_id] = nil
	     cookies[:user_id] = {:value=>"",:expires=>1.year.from_now,:domain=>'trikr.com'}
             redirect_to "/login"
  end
  
  def forget_password
      url = request.subdomains
      @company = Company.find(:first,:conditions=>["url = ?",url])
      @page_title = @company.name if @company
      unless request.get?
      uname = params[:user][:username]
      if uname.match("@") 
         user = User.find(:first,:conditions =>["company_id = ? and email = ?",@company.id,uname])
      else
         user = User.find(:first,:conditions =>["company_id = ? and username = ?",@company.id,uname])
      end

      if user
        Notifier.deliver_notify('signup',user.email,user,user.lang)
        msg = "We have send your password to:" + user.email
      else 
        msg = "Sorry, but we have no this user in our database"
      end

      render :update do |page|
        page.hide 'loading'
	page.replace_html 'msg',msg
      end
      end
  end

  def success
		@user  = User.find(session[:user_id])
	        session[:pid] = 0
		session[:show] = nil

        @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed != 1 AND project_id in(select project_id from tasks where user_id = ? AND role='Manager')",@user.id],:order => "user_id,id desc"
		@user.reload
		@projects = @user.active_projects
        render :partial=>'project' if request.post?
  end
  def managed_project
        @pid = params[:id].to_i
		session[:pid] = @pid
		@user  = session[:user]
		@user.reload
		@projects = @user.active_projects
        @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed != 1 AND project_id = #{@pid}",@user.id],:order => "user_id,id desc"
		render :update do |page|
		  page.replace_html 'managed_projects',:partial=>'managed_timelogs' 
		  page.replace_html 'menuc',:partial=>'menu3' 
		end
		#page.replace_html 'managed_projects',:partial=>'managed_timelogs'if :page == 1 or request.post?
  end

  def confirm
		@user  = session[:user]
		t = TimeLog.find(params[:id])
		t.confirmed = 1
		t.save

		if session[:pid] == 0
          @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed != 1 AND project_id in(select project_id from tasks where user_id = ? AND role='Manager')",@user.id],:order=>"id DESC"
		else
          @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed != 1 AND project_id = #{session[:pid]}",@user.id],:order=>"id DESC"
		end
		render :partial=>'managed_timelogs' 
  end
  def unconfirm
		@user  = session[:user]
		t = TimeLog.find(params[:id])
		t.confirmed = 0
		t.save

		if session[:pid] == 0
           @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed = 1 AND project_id in(select project_id from tasks where user_id = ? AND role='Manager')",@user.id],:order => "id desc"
		else
           @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed = 1 AND project_id = #{session[:pid]}",@user.id],:order => "id desc"
		end
		render :partial=>'managed_timelogs' 
  end

  def show_logs
		@user  = session[:user]
		session[:pid] = params[:pid].to_i if not params[:pid].nil?
		session[:show] = params[:show] if not params[:show].nil?
		@projects = @user.active_projects
		if session[:show] == "confirmed"
		  if session[:pid] == 0
            @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed = 1 AND project_id in(select project_id from tasks where user_id = ? AND role='Manager')",@user.id],:order => "user_id,id desc"
	      else
            @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed = 1 AND project_id = #{session[:pid]}",@user.id],:order => "user_id,id desc"
		  end
		elsif session[:show] == "unconfirmed"
		  if session[:pid] == 0
            @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed = 0 AND project_id in(select project_id from tasks where user_id = ? AND role='Manager')",@user.id],:order => "user_id,id desc"
		  else
            @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed = 0 AND project_id = #{session[:pid]} ",@user.id],:order => "user_id,id desc"
		  end
        else
		  @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["project_id in(select project_id from tasks where user_id = ? AND role='Manager')",@user.id],:order => "user_id,id desc"
		end
		render :partial=>'managed_timelogs' if :page == 1 or request.post?
  end

  def confirm_page
		@user  = session[:user]
		@pid=0
		@projects = @user.active_projects
		@tlogs = TimeLog.find(:all,:conditions=>["confirmed != 1 AND project_id in(select project_id from tasks where user_id = #{@user.id} AND role='Manager')"],:order=>"id DESC",:limit=> "10",:offset=>"0") 
		@tlogs.each do |t|
		 t.confirmed = 1
		 t.save
		end
		TimeLog.reload
        @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed = 1 AND project_id in(select project_id from tasks where user_id = ? AND role='Manager')",@user.id],:order => "id desc"
		render :partial=>'managed_timelogs'  if :page == 1 or request.post?
  end
  def unconfirm_page
		@user  = session[:user]
		@pid=0
		@projects = @user.active_projects
		ActiveRecord::Base.connection.execute("UPDATE time_logs SET confirmed = 0 WHERE confirmed = 1 AND project_id in(select project_id from tasks where user_id = #{@user.id} AND role='Manager') ORDER BY id DESC LIMIT 10")
		ActiveRecord::Base.connection.reload
        @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed = 0 AND project_id in(select project_id from tasks where user_id = ? AND role='Manager')",@user.id],:order => "id desc"
		render :partial=>'managed_timelogs'  if :page == 1 or request.post?
  end

  def show_completed_projects
      @projects = session[:user].completed_projects
      render :partial=>'project' 
  end
  def show_all_projects
      @projects = session[:user].projects
      render :partial=>'project'
  end
  def destroy
      TimeLog.find(params[:id]).destroy
		@user  = session[:user]
		session[:pid] = params[:pid].to_i if not params[:pid].nil?
		session[:show] = params[:show] if not params[:show].nil?
		@projects = @user.active_projects
		if session[:show] == "confirmed"
		  if session[:pid] == 0
            @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed = 1 AND project_id in(select project_id from tasks where user_id = ? AND role='Manager')",@user.id],:order => "id desc"
	      else
            @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed = 1 AND project_id = #{session[:pid]}",@user.id],:order => "id desc"
		  end
		elsif session[:show] == "unconfirmed"
		  if session[:pid] == 0
            @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed = 0 AND project_id in(select project_id from tasks where user_id = ? AND role='Manager')",@user.id],:order => "id desc"
		  else
            @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["confirmed = 0 AND project_id = #{session[:pid]} ",@user.id],:order => "id desc"
		  end
        else
		  @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["project_id in(select project_id from tasks where user_id = ? AND role='Manager')",@user.id],:order => "id desc"
		end
		render :partial=>'managed_timelogs' if :page == 1 or request.post?
  end
end









